import { useUserStore } from '@/stores/modules/user.js'; // 假设你有一个状态管理

const app = getApp();

Page({
  data: {
    loginForm: {
      username: '',
      password: '',
      usernameType: 0  // 0表示用户名, 1表示邮箱
    },
    forgotPassword: false,
    isShow1: false,
    isShow2: false,
    forgotPasswordForm: {
      mail: '',
      identifyingCode: '',
      newPassword: '',
      confirm: ''
    },
    attempt: 3,
    defaultMessage: '验证失败,您还剩下3次机会',
    fullscreenLoading: false
  },

  onInputChange(e) {
    const { name } = e.currentTarget.dataset;
    const value = e.detail.value;
    this.setData({
      [name]: value
    });
  },

  toggleForgotPassword() {
    this.setData({
      forgotPassword: !this.data.forgotPassword,
      isShow1: false,
      isShow2: false
    });
  },

  async onLogin(e) {
    const { username, password } = this.data.loginForm;

    if (this.data.attempt <= 0) {
      wx.showToast({ title: '您近期操作频繁,请1分钟后再试', icon: 'none' });
      return;
    }

    this.setData({ fullscreenLoading: true });

    try {
      const res = await wx.request({
        url: '/api/v2/login',
        method: 'POST',
        data: { username, password },
      });

      if (res.data.code === 200) {
        const accessToken = res.data.data.accessToken;
        app.globalData.accessToken = accessToken;
        wx.setStorageSync('loginInfo', JSON.stringify(this.data.loginForm));
        await this.getUser(accessToken);
      } else {
        this.onFail();
        wx.showToast({ title: res.data.msg, icon: 'none' });
      }
    } catch (error) {
      wx.showToast({ title: '发生未知错误，请稍后再试', icon: 'none' });
    } finally {
      this.setData({ fullscreenLoading: false });
    }
  },

  async getUser(accessToken) {
    try {
      const res = await wx.request({
        url: '/api/v2/users/list?flag=1',
        method: 'POST',
        header: { token: accessToken },
      });

      if (res.data.code === 200) {
        const userStore = useUserStore();
        const userData = res.data.data;
        
        userStore.setUserProperty('schoolId', userData.schoolId);
        userStore.setUserProperty('gradeId', userData.gradeId);
        userStore.setUserProperty('classId', userData.classId);
        userStore.setUserProperty('districtId', userData.districtId);
        userStore.setUserProperty('cityId', userData.cityId);
        userStore.setUserProperty('userRoleId', userData.userRoleId);
        userStore.setUserProperty('status', userData.status);
        userStore.setUserProperty('name', userData.name);
        userStore.setUserProperty('school', userData.school);
        userStore.setUserProperty('grade', userData.grade);
        userStore.setUserProperty('className', userData.className);
        userStore.setUserProperty('city', userData.city);
        userStore.setUserProperty('district', userData.district);
        userStore.setUserProperty('mail', userData.mail);
        userStore.setUserProperty('identityId', userData.identityId);
        userStore.setUserProperty('number', userData.number);
        userStore.setUserProperty('phone', userData.phone);
        userStore.setUserProperty('address', userData.address);
        userStore.setUserProperty('sex', userData.sex);
        userStore.setUserProperty('isUse', true);
        userStore.setUserProperty('token', accessToken);
        userStore.setUserProperty('id', userData.id);
        userStore.setUserProperty('age', userData.age);
        
        // 跳转到相应页面
        this.redirectUser(userData.userRoleId);
      } else {
        wx.showToast({ title: res.data.msg, icon: 'none' });
      }
    } catch (error) {
      wx.showToast({ title: '发生未知错误，请稍后再试', icon: 'none' });
    }
  },

  redirectUser(userRoleId) {
    if (userRoleId == 4 || userRoleId == 7) {
      wx.redirectTo({ url: '/student/tests' });
    } else if (userRoleId == 2) {
      wx.redirectTo({ url: '/school/center/schoolPreview' });
    } else if (userRoleId == 9) {
      wx.redirectTo({ url: '/teacher/center/SchoolManagement/studentList' });
    } else {
      wx.redirectTo({ url: '/nav' });
    }
  },

  onFail() {
    this.data.attempt--;
    if (this.data.attempt < 0) {
      wx.setStorageSync('forbid', '1'); // 禁用操作
      wx.showToast({ title: '操作频繁，请稍后再试', icon: 'none' });
      return;
    }
    const remainingAttempts = this.data.attempt;
    this.setData({
      defaultMessage: `验证失败,您还剩下${remainingAttempts}次机会`
    });
  },

  async onGetIdentifyingCode(e) {
    const { mail } = this.data.forgotPasswordForm;

    if (!mail) {
      wx.showToast({ title: '请输入邮箱', icon: 'none' });
      return;
    }

    try {
      const res = await wx.request({
        url: '/api/v2/users/recovery-password',
        method: 'POST',
        data: { mail },
      });

      if (res.data.code === 200) {
        wx.showToast({ title: '已成功发送验证码,请注意查看', icon: 'success' });
      } else {
        wx.showToast({ title: res.data.msg, icon: 'none' });
      }
    } catch (error) {
      wx.showToast({ title: '发生未知错误，请稍后再试', icon: 'none' });
    }
  },

  async onConfirmPassword(e) {
    const { newPassword, confirm } = this.data.forgotPasswordForm;

    if (newPassword !== confirm) {
      wx.showToast({ title: '两次密码不匹配', icon: 'none' });
      return;
    }

    try {
      const res = await wx.request({
        url: '/api/v2/users/recovery-password/verify',
        method: 'POST',
        data: { mail: this.data.forgotPasswordForm.mail, newPassword },
      });

      if (res.data.code === 200) {
        wx.showToast({ title: '更改密码成功,您现在可以使用新密码进行登录', icon: 'success' });
        this.setData({ forgotPassword: false, isShow2: false });
      } else {
        wx.showToast({ title: res.data.msg, icon: 'none' });
      }
    } catch (error) {
      wx.showToast({ title: '发生未知错误，请稍后再试', icon: 'none' });
    }
  }
});
